clear
matrix=readmatrix('raw.xlsx');
matrix=matrix(:,4:11);
%%Convert token to consumption, and convert return to price
p0=matrix(:,1:4);
q0=matrix(:,5:8);
q0=p0.*q0;
p0=1./p0;
matrix=[p0,q0];


%%Sort price vector from low to high for each subject. Call them bundle
%%1, bundle 2,...
matrix1=zeros(41*103,8);
for i=1:103
    pq=matrix((i-1)*41+1:i*41,:);
    pq=sortrows(pq,[1 2 3 4]);
    matrix1((i-1)*41+1:i*41,:)=pq;
end
matrix2=reshape(matrix1',8*41,103)';

%%Permute bundle 1 from all subjects; Permute bundle 2 from all
%%subjects... each row becomes a randomly sampled dataset. Repeat 100 times.
matrix_rdnsmpl=[];
matrix3=reshape(matrix2,103,8,41);
for j=1:100
    for i=1:41
    rdnint=randperm(103);
    matrix3(:,:,i)=matrix3(rdnint(1:103),:,i);
    end
    matrix_rdnsmpl_j=reshape(matrix3,103,8*41);
    matrix_rdnsmpl=[matrix_rdnsmpl;matrix_rdnsmpl_j];
end
matrix_rdnsmpl=reshape(matrix_rdnsmpl',8,41*103*100)';


%Randomly generate 103*100 individual dataset as long as the tokens sum to
%100
matrix_rdn_q0=randfixedsum(4,41*103*100,100,0,100)';
matrix_rdn_p0=repmat(matrix(:,1:4),100,1);
matrix_rdn_q0=matrix_rdn_p0.*matrix_rdn_q0;
matrix_rdn_p0=1./matrix_rdn_p0;
matrix_rdn=[matrix_rdn_p0,matrix_rdn_q0];


%%GARP test on the randomly generate dataset matrix_rdn and the randomly sampled dataset matrix_rdnsmpl.  
result=[];
parfor i=1:10300
    p1=matrix_rdn((i-1)*41+1:i*41,1:4);
    q1=matrix_rdn((i-1)*41+1:i*41,5:8);
    p2=matrix_rdnsmpl((i-1)*41+1:i*41,1:4);
    q2=matrix_rdnsmpl((i-1)*41+1:i*41,5:8);
    ccei1=emax(p1,q1);
    ccei2=emax(p2,q2);
    ccei=[ccei1,ccei2];
    result=[result;ccei];
end

%%Compute the passing rates
for i=1:2
r(i,1)=sum(result(:,i)==1)/10300;
r(i,2)=sum(result(:,i)>=0.99)/10300;
r(i,3)=sum(result(:,i)>=0.95)/10300;
r(i,4)=sum(result(:,i)>=0.90)/10300;
end

T1=array2table(result,'VariableNames',{'CCEI10300random','CCEI10300resampled'});
T2=array2table(r,'VariableNames',{'e=1','e>=0.99','e>=0.95','e>=0.90'},'Rownames',{'random';'resampled'});
filename = 'Powertest.xlsx';
writetable(T1,filename,'Sheet',1)
writetable(T2,filename,'Sheet',2,'WriteRowNames',true)